package com.zjw.socket.demo.starter.pool;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;

import java.util.HashSet;
import java.util.Set;

public final class NetSocketPoolImpl implements NetSocketPool {

  private static final String TAG = "NetSocketPoolImpl";

  public static NetSocketPoolImpl pool() {
    return new NetSocketPoolImpl();
  }

  private final Set<NetSocket> netSockets = new HashSet<>();

  @Override
  public void addConnect(NetSocket socket) {
    synchronized (netSockets) {
      netSockets.add(socket);
    }
  }

  @Override
  public void removeConnect(NetSocket socket) {
    synchronized (netSockets) {
      netSockets.remove(socket);
    }
    socket.close();
  }

  @Override
  public void publishBuffer(Buffer buffer) {
    synchronized (netSockets) {
      for (NetSocket netSocket : netSockets) {
        netSocket.write(buffer);
      }
    }
  }

  @Override
  public void close() {
    synchronized (netSockets) {
      for (NetSocket netSocket : netSockets) {
        netSocket.close();
      }
      netSockets.clear();
    }
  }

  @Override
  public int count() {
    synchronized (netSockets) {
      return netSockets.size();
    }
  }
}
